package puzzle.masyu2.solver;

import puzzle.common.data.HatanException;
import puzzle.common.point.Direction;
import puzzle.masyu2.data.FlagHelper;
import puzzle.masyu2.data.MasyuBoard;

class BasicLineRule extends MasyuCellRule {

	public boolean apply(MasyuBoard b, int x, int y) throws HatanException {
		if (b.isSatisfied(x, y)) {
			return false;
		}

		int existFlags = b.getExistFlags(x, y);
		int forbiddenFlags = b.getForbiddenFlags(x, y);

		int existCount = FlagHelper.getNumberOfFlags(existFlags);
		int forbiddenCount = FlagHelper.getNumberOfFlags(forbiddenFlags);

		boolean isChanged = false;
		if (existCount == 2 || forbiddenCount == 3) {
			for (Direction d : FlagHelper.getDirectionsForFlags(~existFlags)) {
				isChanged |= b.setForbiddenFlag(x, y, d);
			}
		} else if (existCount == 1 && forbiddenCount == 2) {
			for (Direction d : FlagHelper.getDirectionsForFlags(~(existFlags | forbiddenFlags))) {
				isChanged |= b.setExistFlag(x, y, d);
			}
		} else if (existCount >= 3 || (existCount == 1 && forbiddenCount == 3)) {
			throw new HatanException();
		}
		return isChanged;
	}

}
